package com.bee.gateway.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.bee.commons.cache.CacheService;
import com.bee.gateway.common.constants.GatewayRedisConst;
import com.bee.gateway.server.service.RoutesService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Damin.yang
 * @date 2019/07/30 18:01
 */
@Service
@Slf4j
public class RoutesServiceImpl implements RoutesService {

    @Autowired
    private CacheService cacheService;

    private Map<String, RouteDefinition> routeDefinitionMap = Maps.newHashMap();

    @Override
    public void loadRouteDefinition() {
        Map<String, RouteDefinition> map = Maps.newHashMap();
        Set<String> keys = cacheService.keys(GatewayRedisConst.ROUTES_PREFIX);
        log.info(">>> load gateway redis key size {}, datas: {}", keys.size(), JSON.toJSONString(keys));
        if (CollectionUtils.isNotEmpty(keys)) {
            List<Object> list = cacheService.multiGet(keys);
            log.info("load keys datas: {}", JSON.toJSONString(list));
            list.forEach(o -> {
                RouteDefinition routeDefinition = JSON.parseObject((String) o, RouteDefinition.class);
                map.put(routeDefinition.getId(), routeDefinition);
            });
        }
        routeDefinitionMap = map;
    }

    @Override
    public Collection<RouteDefinition> getRouteDefinition() {
        return routeDefinitionMap.values();
    }

    @Override
    public void save(RouteDefinition routeDefinition) {
        routeDefinitionMap.put(routeDefinition.getId(), routeDefinition);
    }

    @Override
    public void delete(String routeId) {
        routeDefinitionMap.remove(routeId);
    }
}
